<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 16/9/21
 * Time: 下午9:18
 */
class ModReal{
	
	public static function getLink($server='192.168.1.10', $dbName='',$port){
		$logServer = PubServer::getLogServerByDevId($server);
		if(empty($logServer)){
			return false;
		}
	
		$username = Yii::app()->params['ModLog']['username'];
		$password = Yii::app()->params['ModLog']['password'];
		$config = array(
				'dsn'       =>  'mysql:host='.$logServer.';port='.$port,
				'username' =>  $username,
				'password' =>  $password,
		);
	
		return new PubDbLink($config, $dbName);
	}
	
	public function selectByType($type, $params){
		
	    $tblInfo = 'tbllog_online_num';
        $fields = "*";
       
        $where  = " WHERE ctime BETWEEN :begin AND :end ";
        $args   = array(
            'begin' => strtotime($params['time_start'] . ' 00:00:00'),
            'end'   => strtotime($params['time_end'] . ' 23:59:59')
        );

        if(!empty($params['server'])){
            $where .= " AND server=:server ";
            $args['server'] = $params['server'];
        }

        $dbLink = self::getLink($params['server'],'',$params['port']);
        
        $dbName = 'mangologdb';

        $table  = "(";
        for($start=strtotime($params['time_start']), $end=strtotime($params['time_end']), $i=7;$start<=$end && $i>0; $start+=86400, $i--){                   	
        	$oneDb  = $dbName . '_' . date('Ym', $start);
            $oneTb  = $tblInfo . '_' . date('Ymd', $start);
            $table .= " (SELECT * FROM {$oneDb}.{$oneTb} {$where}) UNION ALL";
        }
        $table = substr($table, 0, -9);
        $table .= ') AS tbl';
        
        $sql = "SELECT {$fields} FROM {$table} {$where} ORDER BY ctime desc";

        return $dbLink->query($sql, $args);
	}

    public function selectByType1($type, $params){
//     	var_dump($params);
        $typeInfo = $this->typeInfo($type);

        if(!$typeInfo){
            return array();
        }
        
        $args = array(
        		'begin'     => strtotime($params['time_start']),
        		'end'       => strtotime($params['time_end'].' 23:59:59'),
        		//'platform'  => $params['os'],
        		//'SID'       => $params['server']
        );
        
        
        $user = AccAuth::me();

        $beginMonth = date('Ym', strtotime($params['time_start']));
        $endMonth   = date('Ym', strtotime($params['time_end']));
        if($beginMonth == $endMonth){
            $table = $typeInfo['table'].$beginMonth;
            $sql = "SELECT RecDate,'{$typeInfo['kpi']}' AS KPI,{$typeInfo['col']} AS Value FROM {$table}
                WHERE RecDate BETWEEN :begin AND :end AND {$typeInfo['col']}>0 ";
            
            if($params['os'] != 'ALL' || $user['IsViewAll'] != 1){
            	$sql .= " AND Platform=:platform ";
            	$args[':platform'] = $params['os'];
            }
            
            if($params['os'] == 'ALL' && $params['server'] == 'ALL'){  //都为all，查询专服下的所有渠道的服务器
            	$modServer = new ModServer();
            	$list = $modServer->getServerForSpecialId($params['g'],$params['special_id']);
            	$sql .= " AND ( ";
            	foreach ($list as $key=>$val){
            		$sql .= " SID = '{$val['develop_id']}'  or";
            	}
            	$sql = substr($sql, 0, -2);
            	$sql .= " ) ";
            }else{
            	$sql .= " AND SID=:SID ";
            	$args[':SID'] = empty($params['server']) ? 'ALL' : $params['server'];
            }
            
            
//             $sql .= " AND Platform=:platform ";
//             $sql .= " AND SID=:SID";
        }else{
            $i      = 0;
            $sql    = '';
            while ($beginMonth <= $endMonth && $i<120){
                $table = $typeInfo['table'].$beginMonth;
                $sql .= "(SELECT RecDate,'{$typeInfo['kpi']}' AS KPI,{$typeInfo['col']} AS Value FROM {$table}
                  WHERE RecDate BETWEEN :begin AND :end AND {$typeInfo['col']}>0 ";
                
                if($params['os'] != 'ALL' || $user['IsViewAll'] != 1){
                	$sql .= " AND Platform=:platform ";
                	$args[':platform'] = $params['os'];
                }
                
                if($params['os'] == 'ALL' && $params['server'] == 'ALL'){  //都为all，查询专服下的所有渠道的服务器
                	$modServer = new ModServer();
                	$list = $modServer->getServerForSpecialId($params['g'],$params['special_id']);
                	$sql .= " AND ( ";
                	foreach ($list as $key=>$val){
                		$sql .= " SID = '{$val['develop_id']}'  or";
                	}
                	$sql = substr($where, 0, -2);
                	$sql .= " ) ";
                }else{
                	$sql .= " AND SID=:SID ";
                	$args[':SID'] = empty($params['server']) ? 'ALL' : $params['server'];
                }                
                
//                 $sql .= " AND Platform=:platform ";
//                 $sql .= " AND SID=:SID";
//                 $sql .= " ) UNION ";
//                   AND Platform=:platform
//                   AND SID=:SID) UNION ";

                $beginMonth = date('Ym', strtotime('+1 month', strtotime($beginMonth.'01')));
                $i++;
            }
            $sql = substr($sql, 0, -6);
        }

        

        $dbName = ucfirst($params['g']).'RealTimeDB';
        $dbLink = new PubDbLink('dbSelf', $dbName);

//         echo $sql;
//         var_dump($args);
        return $dbLink->query($sql, $args);
    }

    public function typeInfo($type){
        $config = array(
            'login' => array(
                'table' => 'tblRealTime_Login_',
                'kpi'   => 'LoginUser',
                'col'   => 'CumLoginUser',
            ),
            'online' => array(
                'table' => 'tblRealTime_Online_',
                'kpi'   => 'Online',
                'col'   => 'OnlineNum',
            ),
            'reg' => array(
                'table' => 'tblRealTime_Reg_',
                'kpi'   => 'RegUser',
                'col'   => 'CumRegUser',
            ),
            'pay' => array(
                'table' => 'tblRealTime_Pay_',
                'kpi'   => 'Paymoney',
                'col'   => 'CumPayMoney',
            )
        );
        return (isset($config[$type])) ? $config[$type] : false;
    }

}
